//
//  FormatUtil.m
//  TableBarControllerDemo
//
//  Created by 边果互动 on 2021/3/17.
//

#import "FormatUtil.h"

@implementation FormatUtil

#pragma mark - 从字典中获取NSString
+ (NSString *) encodeStringFromDic: (NSDictionary *) dic andKey: (NSString *) key {
    if (key == nil || [dic isKindOfClass:[NSNull class]] ||![dic isKindOfClass:[NSDictionary class]]) {
        return @"";
    }
    @try {
        id temp = [dic objectForKey:key];
        if ([temp isKindOfClass:[NSString class]]) {
            return [NSString stringWithFormat:@"%@",temp];
        } else if ([temp isKindOfClass:[NSNumber class]]) {
            return [NSString stringWithFormat:@"%@",[temp stringValue]];
        }
    } @catch (NSException *exception) {
        return @"";
    }
    return @"";
}

#pragma mark - 从字典中获取Number
+ (NSNumber *) encodeNumberFromDic: (NSDictionary *) dic andKey: (NSString *) key {
    @try {
        id temp = [dic objectForKey:key];
        if ([temp isKindOfClass:[NSString class]]) {
            return [NSNumber numberWithDouble:[temp doubleValue]];
        } else if ([temp isKindOfClass:[NSNumber class]]) {
            return temp;
        }
    } @catch (NSException *exception) {
        return nil;
    }
    return nil;
}

#pragma mark - 获取当前时间
+(NSString *) getCurrentTime: (NSString *) pattern {
    // 获取系统当前时间
    NSDate * date = [NSDate date];
    NSTimeInterval sec = [date timeIntervalSinceNow];
    NSDate * currentDate = [[NSDate alloc] initWithTimeIntervalSinceNow:sec];
    
    //设置时间输出格式：
    NSDateFormatter * df = [[NSDateFormatter alloc] init];
    [df setDateFormat:pattern];
    NSString * na = [df stringFromDate:currentDate];
    return na;
}

#pragma mark - Date转字符串
+(NSString *) date2Str: (NSDate *) date andWithPattern: (NSString *) pattern {
    //设置时间输出格式：
    NSDateFormatter * df = [[NSDateFormatter alloc] init];
    [df setDateFormat:pattern];
    NSString * na = [df stringFromDate:date];
    return na;
}

#pragma mark - 时间戳转时间
+ (NSString *) str2Time:  (NSString *) timeStr andWithPattern: (NSString *) pattern {
    long long time = [timeStr longLongValue];
    //如果服务器返回的时间戳是13位的（毫秒），就要执行下面的方法
//    time /= 1000;
    NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:time];
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:pattern];
    return [format stringFromDate:date];
}

@end
